<template>
  <view class="goodsEdit mPadBottom">
    <!-- #ifndef MP-TOUTIAO -->
    <singleHeader :pageTitle="getTitle"></singleHeader>
    <!-- #endif -->

    <view class="editHeader">
      <u-input
        v-model="name"
        :placeholder="$t('newAdmin.goods.titP')"
        type="text"
        maxlength="38"
        clearable
      ></u-input>
      <view class="file">
        <toolsFile
          :fileList="goods_pic_list"
          :max="9"
          @success="(e) => fileSuccess('goods_pic_list', e)"
          @remove="(i) => goods_pic_list.splice(i, 1)"
        ></toolsFile>
      </view>
    </view>

    <view class="mForm">
      <view class="mForBox">
        <!-- <view class="mFormItem" @click="openPicker('showProductTypePop')">
          <view class="let">{{ $t("newAdmin.goods.goodsType") }}</view>
          <view class="rig">
            <view class="inp">
              <view class="input">{{
                getPickerValue(productList, product_type, "id", "name")
              }}</view>
            </view>
            <view class="icon">
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view> -->
        <u-select
          v-model="showProductTypePop"
          mode="single-column"
          value-name="id"
          label-name="name"
          :list="productList"
          @confirm="
            (e, i) => bindPickerChange(e, 'single-column', 'product_type')
          "
        ></u-select>

        <view class="mFormItem" @click="openPicker('showCategoryPop')">
          <view class="let"
            ><text class="ts">*</text>{{ $t("agency.class") }}</view
          >
          <view class="rig">
            <view class="inp">
              <view class="input">
                <uni-data-picker
                  ref="showCategoryPop"
                  placeholder="请选择"
                  :popup-title="$t('agency.class')"
                  :localdata="cat"
                  :map="{
                    text: 'name',
                    value: 'id',
                  }"
                  v-model="classes"
                  @change="onchange"
                >
                </uni-data-picker>
              </view>
            </view>
            <view class="icon">
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
      </view>

      <view class="mForBox">
        <view class="mFormItem">
          <view class="let"
            ><text class="ts">*</text>{{ $t("list.price") }}</view
          >
          <view class="rig">
            <view class="inp">
              <u-input
                input-align="right"
                type="digit"
                v-model="price"
                placeholder="请输入价格"
                @blur="(e) => changeInp(e, 'price')"
              ></u-input>
            </view>
            <view class="inpSort">元</view>
            <view class="icon">
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
        <view class="mFormItem">
          <view class="let">成本价</view>
          <view class="rig">
            <view class="inp">
              <u-input
                input-align="right"
                type="digit"
                v-model="cost_price"
                placeholder="请输入成本价"
                @blur="(e) => changeInp(e, 'cost_price')"
              ></u-input>
            </view>
            <view class="inpSort">元</view>
            <view class="icon">
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
        <view class="mFormItem">
          <view class="let">{{ $t("admin.original") }}</view>
          <view class="rig">
            <view class="inp">
              <u-input
                input-align="right"
                type="digit"
                v-model="original_price"
                :placeholder="$t('admin.noOriginal')"
                @blur="(e) => changeInp(e, 'original_price')"
              ></u-input>
            </view>
            <view class="inpSort">元</view>
            <view class="icon">
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
      </view>

      <view class="mForBox">
        <view class="mFormItem">
          <view class="let"
            ><text class="ts">*</text>{{ $t("newAdmin.goods.num") }}</view
          >
          <view class="rig">
            <view class="inp">
              <u-input
                input-align="right"
                type="number"
                v-model="goods_num"
                :placeholder="$t('admin.noCount')"
                @blur="(e) => changeInp(e, 'goods_num')"
              ></u-input>
            </view>
            <view class="inpSort">件</view>
            <view class="icon">
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
        <view class="mFormItem">
          <view class="let">{{ $t("admin.article") }}</view>
          <view class="rig">
            <view class="inp">
              <u-input
                input-align="right"
                type="text"
                v-model="goods_no"
                :placeholder="$t('admin.noArticle')"
              ></u-input>
            </view>
          </view>
        </view>
      </view>

      <view class="mForBox">
        <view class="mFormItem" @click="openPop('showPopAttr')">
          <view class="let">{{ $t("admin.spec") }}</view>
          <view class="rig">
            <view class="attrText"
              >+ {{ $t("admin.add") + $t("admin.spec") }}</view
            >
            <view class="icon">
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
        <view class="mFormItem" v-show="attr.length">
          <view class="let">{{ $t("admin.spec") }}</view>
          <view class="rig">
            <view class="attr" v-show="attr.length">
              <view v-for="(item, index) of attr" :key="index">
                <view class="attrItem" v-if="index < 7">
                  <image :src="item.pic" mode="aspectFill"></image>
                </view>
              </view>

              <view class="attrText"
                >{{ attr.length }}个{{ $t("admin.spec") }}</view
              >
            </view>
          </view>
        </view>
      </view>

      <view class="mForBox">
        <view class="mFormItem" @click="openPop('showEditor')">
          <view class="let">图文设置</view>
          <view class="rig">
            <view class="icon">
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
      </view>

      <view class="mForBox">
        <view class="mFormItem" @click="openPop('showLogisticsPop')">
          <view class="let">{{ $t("newAdmin.goods.logisticsSettings") }}</view>
          <view class="rig">
            <view class="icon">
              <i class="iconfont icon-arrow-right"></i>
            </view>
          </view>
        </view>
      </view>
    </view>

    <view class="editFooter">
      <u-button
        :customStyle="customStyle"
        :hoverStartTime="hoverStartTime"
        :disabled="disabled"
        @click="goEdit(-1)"
        >{{ getTitle }}</u-button
      >
    </view>

    <pageEditor
      ref="pageEditor"
      v-show="showEditor"
      :show="showEditor"
      :value="detail"
      @cancel="showEditor = false"
    ></pageEditor>
    <pageLogistics
      ref="pageLogistics"
      v-show="showLogisticsPop"
      :show="showLogisticsPop"
      :hoverStartTime="hoverStartTime"
      :customStyle="customStyle"
      :postageList="postage"
      :goodsDeliveryType="goods_delivery_type"
			:disabledDeliveryType="disabledDeliveryType"
    ></pageLogistics>
    <pagePopAttr
      ref="pagePopAttr"
      v-show="showPopAttr"
      :show="showPopAttr"
      :attr="oldAttr"
      :customStyle="customStyle"
    ></pagePopAttr>
  </view>
</template>

<script>
import singleHeader from "@/components/diySystemPage/components/singleHeader/index.vue";
import toolsFile from "@/components/tools/tools-file";
import pageEditor from "./components/page-editor/robin-editor/editor.vue";
import pagePopAttr from "./components/page-pop-attr.vue";
import pageLogistics from "./components/page-logistics.vue";
import uniDataPicker from "./components/uni-data-picker/components/uni-data-picker/uni-data-picker.vue";

import {
  storeAdminSaveGoods,
  storeAdminGetGoodsEdit,
  storeAdminCatList,
  getPostageData,
} from "@/api/admin";

export default {
  components: {
    singleHeader,
    toolsFile,
    pageEditor,
    pagePopAttr,
    pageLogistics,
    uniDataPicker,
  },

  data() {
    return {
      disabled: false,
      classes: "",
      showEditor: false,
      isFirst: true,
      showPopAttr: false,

      id: undefined,
      hoverStartTime: 10000000,

      is_change_attr: 0,

      postage: [], // 运费设置
      oldAttr: [],
      cat: [], // 分类列表
      goods_delivery_type: [
        { key: "express", value: "快递", checked: false },
        { key: "shop", value: "到店自提", checked: false },
        { key: "delivery", value: "同城配送", checked: false },
      ], // 配送方式

      new_AttrLibrary: [], // 可选规格
      attr: [],
      cat_id: [],

      name: "",

      goods_pic_list: [],
      cover_pic: "",
      product_type: 0, // //商品类型 0: 普通商品，1: 酒店预约，2: 服务预约，3:虚拟商品, 4:积分商品
      price: "",
      cost_price: "",
      original_price: "",
      goods_no: "",
      detail: "",
      goods_num: "",
      // use_attr: 0, //是否开启规格 1.是 0.否

      logistics: {
        freight: "",
        forehead: "0",
        pieces: "0.00",
        delivery_type: [],
      },

      inputStyle: {
        "text-align": "right",
      },
      customStyle: {
        background: "#F0250E",
        color: "#fff",
        borderRadius: "32px",
      },

      showProductTypePop: false,
      showCategoryPop: false,
      showLogisticsPop: false,
			
			disabledDeliveryType: false
      // list: [],
    };
  },

  computed: {
    productList: function () {
      return [
        { id: 0, name: "普通商品" },
        // { id: 1, name: "酒店预约" },
        // { id: 2, name: "服务预约" },
        { id: 3, name: "虚拟商品" },
        { id: 4, name: `${this.stores.integral_name}商品` },
      ];
    },
    getTitle() {
      return !this.id
        ? this.$t("title.addGood")
        : this.$t("cart.edit") + this.$t("newAdmin.order.product");
    },

    getPickerValue() {
      return (list, value, valueName, labelName) => {
        if (!list.length) {
          return;
        }

        return list.find((el) => el[valueName] === value)[labelName];
      };
    },
  },

  onLoad(e) {
    this.$utils.hideShareMenu();

    storeAdminCatList()
      .then((res) => {
        if (res.code === 0) {
          this.cat = res.data;
        }
      })
      .catch(() => {});

    getPostageData().then((res) => {
      this.postage = res.data.postage;
    });

    if (e.id) {
      this.id = e.id;
      this.clearData();
    }
  },

  mounted() {
    this.Emit.$on("logistics", this.logisticsSave);
    this.Emit.$on("editor", this.changeEditor);
    this.Emit.$on("attr", this.changeAttr);
  },

  destroyed() {
    this.Emit.$off("editor");
    this.Emit.$off("logisticsSave");
    this.Emit.$off("attr");
  },

  methods: {
    changeAttr({ attr, is_change_attr }) {
      this.attr = attr;
      this.is_change_attr = is_change_attr;
      this.showPopAttr = false;
    },

    logisticsSave(el) {
      this.logistics = {
        ...el,
      };
      this.showLogisticsPop = false;
    },

    openPop(type) {
      // if (type === "showEditor") {
      //   let { pageEditor } = this.$refs;
      //   // if (this.isFirst) {
      //   //   this.isFirst = false;

      //   //   if (this.detail) {
      //   //     pageEditor.setContents(this.detail);
      //   //   }
      //   // }
      //   // pageEditor.showPopup = true;
      // }
      this[type] = true;
    },

    changeEditor(detail) {
      this.detail = detail;
      this.showEditor = false;
    },

    onchange({ detail }) {
      this.cat_id = detail.value.map((el) => el.value);
    },

    changeInp(e, el) {
      if (e === "") {
        return;
      }

      switch (el) {
        case "goods_num":
          this[el] = parseInt(e);
          break;

        default:
          this[el] = parseFloat(e).toFixed(2);
          break;
      }
    },

    openPicker(el) {
      if (el === "showCategoryPop") return;
      this[el] = true;
    },

    bindPickerChange(e, mode, el) {
      switch (mode) {
        case "single-column":
          this[el] = e[0].value;
          break;
      }
    },

    fileSuccess(e, val) {
      this[e].push({
        url: val,
      });
    },

    clearData() {
      storeAdminGetGoodsEdit({
        id: this.id,
      }).then((res) => {
        if (res.code === 0) {
          let { new_AttrLibrary, info } = res.data;

          this.new_AttrLibrary = new_AttrLibrary;

          // 编辑信息
          if (info.id) {
            this.$nextTick(() => {
              this.oldAttr = info.attr;
              this.cat_id = info.cat_id;
              this.classes = this.cat_id[this.cat_id.length - 1];
              this.goods_pic_list = info.goods_pic_list.map((el) => {
                return { url: el.pic_url };
              });
              this.detail = info.detail;
              this.product_type = parseInt(info.product_type);
              this.price = info.price;
              this.cost_price = info.cost_price;
              this.use_attr = info.use_attr;
              this.name = info.name;
              this.goods_num = info.goods_num;
              this.goods_no = info.goods_no;
              this.original_price = info.original_price;

              this.logistics = {
                delivery_type: info.delivery_type,
                freight: info.freight,
                forehead: info.forehead,
                pieces: info.pieces ? info.pieces : "0.00",
              };

              this.$refs.pageLogistics.setData(this.logistics);
              this.$refs.pagePopAttr.AttrGroupList =
                res.data.AttrGroupList || [];

              this.$nextTick(() => {
                this.$refs.pagePopAttr.save();
              });

              this.goods_delivery_type.forEach((el) => {
                if (info.delivery_type.indexOf(el.key) !== -1) {
                  el.checked = true;
                }
              });
							
							if (info.is_front_centralize || info.is_front_delivery || info.agent_goods_status > 0) {
								this.disabledDeliveryType = true;
							}
            });
          }
        }
      });
    },

    goEdit() {
      let {
        name,
        goods_pic_list,
        cat_id,
        product_type,
        price,
        goods_num,
        // use_attr,
        logistics,
        detail,
        goods_no,
        original_price,
        id,
        attr,
        is_change_attr,
        cost_price,
      } = this;

      if (!name) {
        this.$utils.toast("请输入商品名称");
        return;
      }

      if (!goods_pic_list.length) {
        this.$utils.toast("请上传至少一张商品图片~");
        return;
      }

      if (!cat_id.length) {
        this.$utils.toast("请选择商品分类~");
        return;
      }

      if (price === "") {
        this.$utils.toast("请输入价格~");
        return;
      }
      if (price === "0.00") {
        this.$utils.toast("商品价格不能为0~");
        return;
      }

      if (goods_num === "") {
        this.$utils.toast("请填写库存~");
        return;
      }

      if (!detail) {
        this.$utils.toast("请填写商品详情~");
        return;
      }

      if (!logistics.delivery_type.length) {
        this.$utils.toast("请选择配送方式~");
        return;
      }

      if (
        logistics.delivery_type.indexOf("express") !== -1 &&
        !logistics.freight
      ) {
        this.$utils.toast("请选择运费设置~");
      }

      goods_pic_list = goods_pic_list.map((el) => {
        return {
          pic_url: el.url,
        };
      });

      let goods_info = {
        name,
        product_type,
        cat_id,
        price,
        goods_num: goods_num ? goods_num : "0",
        detail,
        ...logistics,
        cover_pic: goods_pic_list[0].pic_url,
        attr,
        use_attr: attr.length ? 1 : 0,
        goods_pic_list,
        goods_no,
        original_price,
        cost_price,
      };

      if (id) {
        goods_info.id = id;
        goods_info.is_change_attr = is_change_attr;
      }
      this.disabled = true;
      storeAdminSaveGoods({ goods_info }, true)
        .then((res) => {
          this.disabled = false;
          if (res.code === 0) {
            this.$utils.showModal("提示", res.msg, false, () => {
              uni.navigateBack();
            });
            return;
          }

          this.$utils.toast(res.msg);
        })
        .catch(() => {
          this.disabled = false;
        });
    },
  },
};
</script>

<style lang="less" scoped>
.editHeader {
  padding: 0 36rpx;
  background: #fff;

  .file {
    padding: 20rpx 0 30rpx;
  }
}

.mForm {
  background: #f2f2f2;
  padding: 20rpx;
}

.mForBox {
  margin-bottom: 24rpx;
  border-radius: 20rpx;
  overflow: hidden;
}

.mFormItem {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 24rpx;
  height: 100rpx;
  background: #fff;
  font-size: 30rpx;
  color: #1d1d1d;

  .let {
    text {
      color: #f0250e;
    }
  }

  .rig {
    flex: 1;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    margin-left: 10rpx;
  }

  .inp {
    flex: 1;
    text-align: right;
  }

  .input {
    height: 100rpx;
    line-height: 100rpx;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .icon-arrow-right {
    font-size: 22rpx;
    color: #888;
  }

  .inpSort {
    margin-left: 10rpx;
  }

  .attr {
    display: flex;
    align-items: center;

    .attrItem {
      margin: 10rpx 0 0 6rpx;
    }

    image {
      width: 55rpx;
      height: 55rpx;
      border-radius: 4rpx;
      background: #f6f6f6;
    }
  }

  .attrText {
    margin-left: 10rpx;
    color: #f60413;
  }
}

.editFooter {
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 3;
  padding: 10rpx 36rpx calc(env(safe-area-inset-bottom) + 10rpx);
  width: 100%;
  background: #fff;
}

::v-deep {
  .input-value-border {
    border: 0;
  }

  .input-value {
    padding-right: 0;
    height: 100rpx;
    line-height: 100rpx;
    font-size: 30rpx;
    justify-content: flex-end;

    .selected-area,
    .selected-list {
      padding-right: 0;
      justify-content: flex-end;
    }
  }

  .arrow-area {
    display: none;
  }

  .mPadBottom {
    padding-bottom: 150rpx;
  }

  .editFooter {
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 3;
    padding: 10rpx 36rpx calc(env(safe-area-inset-bottom) + 10rpx);
    width: 100%;
    background: #fff;
  }
}

.mPadBottom {
  padding-bottom: 150rpx;
  background: #f2f2f2;
}

.tab {
  display: flex;
  align-items: center;
  margin-top: 24rpx;
  background: #f2f2f2;

  .item {
    width: 50%;
  }
}

::v-deep {
  .uni-checkbox-input {
    border-radius: 50%;
    transform: scale(0.7);
  }

  .uni-checkbox-input-checked {
    border-color: #f0250e !important;
    background: #f0250e;
    color: #fff !important;
  }

  // #ifdef  MP-WEIXIN
  checkbox .wx-checkbox-input {
    border-radius: 50% !important;
    color: #ffffff !important;
    transform: scale(0.7);
  }

  checkbox .wx-checkbox-input.wx-checkbox-input-checked {
    color: #fff;
    background: #f0250e;
    border-color: #f0250e !important;
  }
  // #endif
}
</style>
